package com.color.admin.common.core.base;


import com.color.admin.common.core.exception.BaseException;
import com.color.admin.common.core.result.ResultCode;
import com.color.admin.common.core.utils.web.StringUtils;
import com.color.admin.common.core.utils.web.TokenUtils;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author HaiQiu
 * @date 2021/12/16
 * 公共鉴权配置
 */
public class AuthInterceptor implements AsyncHandlerInterceptor {

    public static final String USER_ID = "userId";
    public static final String USER_NAME = "username";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //处理请求头
        String token = request.getHeader(TokenUtils.TOKEN_KEY);
        if (!StringUtils.isBlank(token)){
            String userId = null;
            String username = null;
            try {
                userId = TokenUtils.getUserIdFormToken(token);
                username = TokenUtils.getUsernameFormToken(token);
            }catch (Exception e){
                throw new BaseException(ResultCode.TOKEN_INVALID);
            }
            request.setAttribute(USER_NAME,username);
            request.setAttribute(USER_ID,userId);
        }
        return true;
    }
}
